package com.zhugang.week06;

/**
 * @program algorithms
 * @description: kthLargest
 * @author: chanzhugang
 * @create: 2022/07/14 18:44
 */
public class KthLargest {

    int count = 0;
    int result;

    /**
     * 剑指offer 54 二叉搜索树的第K大节点
     *
     * @param root
     * @param k
     * @return
     */
    public int kthLargest(TreeNode root, int k) {
        // 中序遍历
        inorder(root, k);
        return result;
    }

    private void inorder(TreeNode root, int k) {
        if (count >= k) {
            // 提前终止递归，剪枝
            return;
        }
        if (root == null) {
            return;
        }
        inorder(root.right, k);
        // 从大到小
        count++;
        if (count == k) {
            result = root.val;
            return;
        }
        inorder(root.left, k);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}